import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/song.dart';
import '../providers/music_provider.dart';

class PlayerPage extends StatefulWidget {
  const PlayerPage({super.key});

  @override
  State<PlayerPage> createState() => _PlayerPageState();
}

class _PlayerPageState extends State<PlayerPage>
    with TickerProviderStateMixin {
  late AnimationController _rotationController;
  late AnimationController _slideController;
  bool _showLyrics = false;

  @override
  void initState() {
    super.initState();
    _rotationController = AnimationController(
      duration: const Duration(seconds: 20),
      vsync: this,
    );
    _slideController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
  }

  @override
  void dispose() {
    _rotationController.dispose();
    _slideController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Consumer<MusicProvider>(
        builder: (context, musicProvider, child) {
          final song = musicProvider.currentSong;
          if (song == null) {
            return const Center(
              child: Text(
                '暂无播放歌曲',
                style: TextStyle(color: Colors.white, fontSize: 18),
              ),
            );
          }

          // 播放时旋转专辑封面
          if (musicProvider.isPlaying) {
            _rotationController.repeat();
          } else {
            _rotationController.stop();
          }

          return Stack(
            children: [
              // 背景渐变
              _buildBackgroundGradient(),
              
              // 主要内容
              SafeArea(
                child: Column(
                  children: [
                    // 顶部导航栏
                    _buildTopBar(context),
                    
                    // 歌曲信息和专辑封面
                    Expanded(
                      flex: 3,
                      child: _buildAlbumSection(song, musicProvider),
                    ),
                    
                    // 播放控制区域
                    Expanded(
                      flex: 2,
                      child: _buildControlSection(musicProvider),
                    ),
                  ],
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildBackgroundGradient() {
    return Container(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Color(0xFF2D1B69),
            Color(0xFF1A1A2E),
            Color(0xFF16213E),
            Color(0xFF0F0F0F),
          ],
        ),
      ),
    );
  }

  Widget _buildTopBar(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          IconButton(
            onPressed: () => Navigator.pop(context),
            icon: const Icon(
              Icons.keyboard_arrow_down,
              color: Colors.white,
              size: 32,
            ),
          ),
          Column(
            children: [
              Text(
                '正在播放',
                style: TextStyle(
                  color: Colors.white.withOpacity(0.7),
                  fontSize: 12,
                ),
              ),
              const Text(
                '我的音乐',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
          IconButton(
            onPressed: () {
              // TODO: 显示更多选项
            },
            icon: const Icon(
              Icons.more_vert,
              color: Colors.white,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildAlbumSection(Song song, MusicProvider musicProvider) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // 专辑封面
        GestureDetector(
          onTap: () {
            setState(() {
              _showLyrics = !_showLyrics;
            });
          },
          child: Container(
            width: 280,
            height: 280,
            margin: const EdgeInsets.symmetric(vertical: 20),
            child: Stack(
              alignment: Alignment.center,
              children: [
                // 外圈装饰
                Container(
                  width: 300,
                  height: 300,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    boxShadow: [
                      BoxShadow(
                        color: Theme.of(context).primaryColor.withOpacity(0.3),
                        blurRadius: 20,
                        spreadRadius: 5,
                      ),
                    ],
                  ),
                ),
                // 旋转的专辑封面
                RotationTransition(
                  turns: _rotationController,
                  child: Container(
                    width: 280,
                    height: 280,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      gradient: RadialGradient(
                        colors: [
                          Theme.of(context).primaryColor,
                          Theme.of(context).primaryColor.withOpacity(0.7),
                          Colors.grey[800]!,
                        ],
                      ),
                    ),
                    child: const Icon(
                      Icons.music_note,
                      size: 80,
                      color: Colors.white,
                    ),
                  ),
                ),
                // 中心圆点
                Container(
                  width: 60,
                  height: 60,
                  decoration: const BoxDecoration(
                    shape: BoxShape.circle,
                    color: Colors.black87,
                  ),
                  child: const Icon(
                    Icons.fiber_manual_record,
                    color: Colors.white,
                    size: 20,
                  ),
                ),
              ],
            ),
          ),
        ),
        
        // 歌曲信息
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 40),
          child: Column(
            children: [
              Text(
                song.name,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 24,
                  fontWeight: FontWeight.bold,
                ),
                textAlign: TextAlign.center,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
              const SizedBox(height: 8),
              Text(
                song.artist,
                style: TextStyle(
                  color: Colors.white.withOpacity(0.7),
                  fontSize: 16,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 4),
              Text(
                song.album,
                style: TextStyle(
                  color: Colors.white.withOpacity(0.5),
                  fontSize: 14,
                ),
                textAlign: TextAlign.center,
              ),
            ],
          ),
        ),
        
        // 收藏和下载按钮
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 20),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              IconButton(
                onPressed: () {
                  // TODO: 收藏功能
                },
                icon: const Icon(
                  Icons.favorite_border,
                  color: Colors.white,
                  size: 28,
                ),
              ),
              const SizedBox(width: 40),
              IconButton(
                onPressed: () {
                  // TODO: 下载功能
                },
                icon: const Icon(
                  Icons.download_outlined,
                  color: Colors.white,
                  size: 28,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildControlSection(MusicProvider musicProvider) {
    return Column(
      children: [
        // 进度条
        _buildProgressBar(musicProvider),
        
        const SizedBox(height: 20),
        
        // 播放控制按钮
        _buildPlayControls(musicProvider),
        
        const SizedBox(height: 20),
        
        // 底部功能按钮
        _buildBottomControls(musicProvider),
      ],
    );
  }

  Widget _buildProgressBar(MusicProvider musicProvider) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: Column(
        children: [
          StreamBuilder<Duration>(
            stream: musicProvider.audioPlayerService.positionStream,
            builder: (context, snapshot) {
              final position = snapshot.data ?? Duration.zero;
              final total = musicProvider.audioPlayerService.totalDuration;
              
              return SliderTheme(
                data: SliderTheme.of(context).copyWith(
                  thumbColor: Theme.of(context).primaryColor,
                  activeTrackColor: Theme.of(context).primaryColor,
                  inactiveTrackColor: Colors.white.withOpacity(0.3),
                  thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 6),
                  trackHeight: 3,
                ),
                child: Slider(
                  value: total.inMilliseconds > 0
                      ? position.inMilliseconds / total.inMilliseconds
                      : 0.0,
                  onChanged: (value) {
                    final newPosition = Duration(
                      milliseconds: (total.inMilliseconds * value).round(),
                    );
                    musicProvider.audioPlayerService.seek(newPosition);
                  },
                ),
              );
            },
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 4),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                StreamBuilder<Duration>(
                  stream: musicProvider.audioPlayerService.positionStream,
                  builder: (context, snapshot) {
                    final position = snapshot.data ?? Duration.zero;
                    return Text(
                      _formatDuration(position),
                      style: TextStyle(
                        color: Colors.white.withOpacity(0.7),
                        fontSize: 12,
                      ),
                    );
                  },
                ),
                Text(
                  musicProvider.currentSong?.duration ?? '00:00',
                  style: TextStyle(
                    color: Colors.white.withOpacity(0.7),
                    fontSize: 12,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPlayControls(MusicProvider musicProvider) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        // 上一首
        IconButton(
          onPressed: musicProvider.previousSong,
          icon: const Icon(
            Icons.skip_previous,
            color: Colors.white,
            size: 40,
          ),
        ),
        
        // 播放/暂停
        Container(
          width: 70,
          height: 70,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: Theme.of(context).primaryColor,
            boxShadow: [
              BoxShadow(
                color: Theme.of(context).primaryColor.withOpacity(0.3),
                blurRadius: 15,
                spreadRadius: 2,
              ),
            ],
          ),
          child: IconButton(
            onPressed: musicProvider.togglePlayPause,
            icon: Icon(
              musicProvider.isPlaying ? Icons.pause : Icons.play_arrow,
              color: Colors.white,
              size: 35,
            ),
          ),
        ),
        
        // 下一首
        IconButton(
          onPressed: musicProvider.nextSong,
          icon: const Icon(
            Icons.skip_next,
            color: Colors.white,
            size: 40,
          ),
        ),
      ],
    );
  }

  Widget _buildBottomControls(MusicProvider musicProvider) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 40),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 播放模式
          IconButton(
            onPressed: () {
              musicProvider.audioPlayerService.togglePlayMode();
            },
            icon: Text(
              musicProvider.audioPlayerService.getPlayModeIcon(),
              style: const TextStyle(fontSize: 20),
            ),
          ),
          
          // 播放列表
          IconButton(
            onPressed: () {
              _showPlaylistDialog(context, musicProvider);
            },
            icon: const Icon(
              Icons.queue_music,
              color: Colors.white,
              size: 28,
            ),
          ),
        ],
      ),
    );
  }

  void _showPlaylistDialog(BuildContext context, MusicProvider musicProvider) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.grey[900],
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (context) => Container(
        height: MediaQuery.of(context).size.height * 0.6,
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '播放列表',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                IconButton(
                  onPressed: () => Navigator.pop(context),
                  icon: const Icon(Icons.close, color: Colors.white),
                ),
              ],
            ),
            const SizedBox(height: 10),
            Expanded(
              child: ListView.builder(
                itemCount: musicProvider.allSongs.length,
                itemBuilder: (context, index) {
                  final song = musicProvider.allSongs[index];
                  final isCurrentSong = musicProvider.currentSong?.id == song.id;
                  
                  return ListTile(
                    leading: Icon(
                      Icons.music_note,
                      color: isCurrentSong 
                          ? Theme.of(context).primaryColor 
                          : Colors.grey,
                    ),
                    title: Text(
                      song.name,
                      style: TextStyle(
                        color: isCurrentSong 
                            ? Theme.of(context).primaryColor 
                            : Colors.white,
                        fontWeight: isCurrentSong ? FontWeight.bold : null,
                      ),
                    ),
                    subtitle: Text(
                      song.artist,
                      style: const TextStyle(color: Colors.grey),
                    ),
                    trailing: isCurrentSong
                        ? Icon(
                            musicProvider.isPlaying ? Icons.volume_up : Icons.pause,
                            color: Theme.of(context).primaryColor,
                          )
                        : null,
                    onTap: () {
                      musicProvider.playSong(song);
                      Navigator.pop(context);
                    },
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    return '$twoDigitMinutes:$twoDigitSeconds';
  }
} 